import { reqShopCartList, reqUpdateShopCart, reqDeleteCart, reqCheckCart } from '@/api'
const state = {
    CartList: []
}
const actions = {
    //获取购物车列表数据
    //获取购物车列表信息
    async getCartList({ commit }) {
        let result = await reqShopCartList()
        if (result.code == 200) {
            commit('CARTLIST', result.data)
        }
    },
    //更新购物车信息
    async UpdateCart({ commit }, { skuId, skuNum }) {
        let result = await reqUpdateShopCart(skuId, skuNum)
        //成功返回ok，失败返回一个失败的promise回调
        if (result.code == 200) {
            return 'ok'
        } else return Promise.reject(new Error('faile'));
    },
    //删除购物车商品
    async DeleteCart({ commit }, skuId) {
        let result = await reqDeleteCart(skuId)
        if (result.code == 200) {
            return 'ok'
        } else return Promise.reject(new Error('faile'));
    },
    //修改商品选中状态
    async CheckCart({ commit }, { skuId, ischecked }) {
        let result = await reqCheckCart(skuId, ischecked)
        if (result.code == 200) {
            return 'ok'
        } else return Promise.reject(new Error('faile'));
    },
    //删除全部勾选商品
    deleteAllCheckedCart({ dispatch, getters }) {
        //context:小仓库，commit【提交mutations修改state】 getters【计算属性】 dispatch【派发action】 state【当前仓库数据】
        let PromiseAll = []
        getters.cartList.cartInfoList.forEach(element => {
            if (element.isChecked == 1) {
                let Promise = dispatch('DeleteCart', element.skuId)
                PromiseAll.push(Promise)
            }
        });
        //只有所有的商品都返回成功的Promise，才会返回成功
        return Promise.all(PromiseAll)
    },
    //全选
    async AllCheckedCart({ dispatch, getters }, isChecked) {
        let PromiseAll = []
        getters.cartList.cartInfoList.forEach(item => {
            //派发action改变每个商品的选中状态
            if (item.isChecked != isChecked) {
                let Promise = dispatch('CheckCart', { skuId: item.skuId, ischecked: isChecked })
                PromiseAll.push(Promise)
            }
        })
        return Promise.all(PromiseAll)
    }
}
const mutations = {
    CARTLIST(state, data) {
        state.CartList = data
    }
}
const getters = {
    cartList(state) {
        return state.CartList[0] || {}
    }
}
export default {
    state, actions, mutations, getters
}